<template>
  <el-form :model="form" :rules="formRules" ref="deptForm" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option :value="item.username" :label="item.username" 
        v-for="item  in  list"
        :key="item.id"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimples } from "@/api/empioyees";
import { addDepartments ,getDepartmentDetail,updateDepartmentDetail} from "@/api/departments";
export default {
  // 侦听组件内prOps中属性或者data函数中属性的变化
  watch:{
    // id:function(nwe,old){
    //   this.loadDepartmentDetail()
    // }
  //   id:{
  //     handler(nwe,old){
  //       this.loadDepartmentDetail()
  //     },
  //     immediate:true
  //   }
  },
    // 接收父组件数据
    props:{
      originList:{
        type:Array,
        required:true
      },

      id:{
        type:String,
        required:true
      },
      isEdit:{
        type:Boolean,
        required:true
      }
    },

    data() {
      // 校验数据 自定义校验
      const validCode = (rule, value, callback) =>{
        // 验证用户输入value值 在整个项目中编码是否已经存在
        // 获取整个部门编码 编码的数组
        let existCodeList = this.originList.map(item => item.code)
        console.log(existCodeList);
        // 判断当前value值 是否在数组中存在
        if(this.isEdit){
          // 如果是编辑的状态 将当前编辑部门的编码从存在的数组中移除 然后再判断
          existCodeList = this.originList.filter(item => item.id !==this.id).map(item => item.code)
        }
        if(existCodeList.includes(value)){
          callback(new Error(`该部门编码${value}与存在,请更换`))
        }else{
          callback()
        }
      }

       // 校验数据 自定义校验
      const validName = (rule, value, callback) =>{
        // 被占用列表
       let existCodeName = this.originList.filter(item => item.pid===this.id).map(item=>item.name)
       console.log(existCodeName);
       console.log(this.originList);
       console.log(this.id);
        // 编辑是招兄弟的处理
        if(this.isEdit){
          // 只能获取到当前编辑的部门id  获取到当前编辑部门的pid
          const  pid =this.originList.find(item => item.id===this.id).pid
          // 通过pid去所有的部门数据中找当前编辑部门的所有兄弟
          const  brothers = this.originList.filter(item =>item.pid===pid)
          // 排除自己
          existCodeName = brothers.filter(item => item.id !==this.id).map(item =>item.name)
        }
        // 判断当前用户输入value 在被占用列表是否存在
        if(existCodeName.includes(value)){

          callback(new Error(`该部门名称${value}与存在,请更换`))
        }else{
          callback()
        }
      }
        return {
            list:[],
            // 收集数据
            form:{
                name:'',
                code:'',
                manager:'',
                introduce:'',
            },
            formRules:{
              name:[
                 {validator: validName, trigger: 'blur' },
                { required: true, message: '请输入部门名称', trigger: 'blur' },
                { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
              ],
              code:[
                { validator: validCode, trigger: 'blur' },
                { required: true, message: '请输入部门编码', trigger: 'blur' },
                { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
              ],
              manager:[
                { required: true, message: '请输入部门负责人', trigger: 'changa' },
              ],
              introduce:[
                { required: true, message: '请输入部门介绍', trigger: 'blur' },
                { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
              ],
            }
        };
    },
    created(){
        this.loadEmployeesSimples()
        if(this.isEdit){
          this.loadDepartmentDetail()
        }
    },
    methods:{
      // 清空表单
      resetFrom(){
        this.$refs.deptForm.resetFields()
        this.form={
                name:'',
                code:'',
                manager:'',
                introduce:'',
            }
      },
      // 修改数据
     async doEdit(){
      try {
         await updateDepartmentDetail(this.form)
        // console.log(res);
        this.$emit('success');
      } catch (error) {
        console.log(error);
      }
     },
      // 获取新增id
    async loadDepartmentDetail(){
      try {
         const res =await getDepartmentDetail(this.id)
        //  console.log(res);
        this.form=res.data
      } catch (error) {
        console.log(error);
      }
    },
      // 编辑
      async  loadEmployeesSimples(){
        try {
          const  res = await getEmployeesSimples()
        // console.log(res);
        this.list=res.data
        } catch (error) {
          console.log(error);
        }       
      },
      // 封装增加部门
     async doAdd(){
        try {
          const res = await addDepartments({pid:this.id,...this.form})
          // console.log(res);
          this.$emit('success');
        } catch (error) {
          console.log(error);
        }
      },
      // 确定按钮
        hSubmit(){
          this.$refs.deptForm.validate((valid)=>{
            if(!valid) return   
            this.isEdit?this.doEdit():this.doAdd()
            
           
          })
        },
        hCancel(){
          this.$emit('close')
        },
    }
}
</script>

<style>

</style>